package com.pureut.production.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.bean.BeanUtils;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.production.domain.CutOrdersDocument;
import com.pureut.production.domain.RollPacking;
import com.pureut.production.domain.RollPackingHistory;
import com.pureut.production.domain.dto.RollPackingDto;
import com.pureut.production.domain.system.domain.SysDocument;
import com.pureut.production.domain.vo.*;
import com.pureut.production.mapper.CutOrdersDocumentMapper;
import com.pureut.production.mapper.RollPackingMapper;
import com.pureut.production.service.RollPackingHistoryService;
import com.pureut.production.service.RollPackingService;
import com.pureut.production.service.WeighingFinishedMaterialProductService;
import com.pureut.system.api.QualityFeginService;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.vo.QualityProductionFreezeVo;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/***
 * 小卷打包实现层
 * Author:C
 * Date:2023/02/17 11:52
 * @DESC
 */
@Service
public class RollPackingServiceImpl extends ServiceImpl<RollPackingMapper, RollPacking> implements RollPackingService {

    @Resource
    RollPackingMapper rollPackingMapper;

    @Resource
    QualityFeginService qualityFeginService;

    @Resource
    CutOrdersDocumentMapper cutOrdersDocumentMapper;

    @Lazy
    @Resource
    WeighingFinishedMaterialProductService weighingFinishedMaterialProductService;

    @Resource
    RollPackingHistoryService rollPackingHistoryService;

    /**
     * 小卷打包列表
     *
     * @param rollPackingVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<RollPackingDto> getList(RollPackingVo rollPackingVo) {

        //小卷打包打印状态
        List<SysDictData> printStatusArray = DictUtils.getDictCache("roll_packing_print_status");
        Map<String, String> printStatusMap = printStatusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //班次
        List<SysDictData> classArray = DictUtils.getDictCache("scheduling_class_info");
        Map<String, String> classMap = classArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));


        List<RollPackingDto> list = rollPackingMapper.getList(rollPackingVo);

        for (RollPackingDto entity : list) {
            entity.setPrintStatusDict(printStatusMap.get(entity.getPrintStatus()));
            entity.setClassDifferenceDict(classMap.get(entity.getClassDifference()));
        }
        return list;
    }

    /**
     * 小卷打包列表(全部数据)
     *
     * @param rollPackingVo
     * @return
     */
    @Override
    public List<RollPackingDto> getAllList(RollPackingVo rollPackingVo) {
        //小卷打包打印状态
        List<SysDictData> printStatusArray = DictUtils.getDictCache("roll_packing_print_status");
        Map<String, String> printStatusMap = printStatusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //班次
        List<SysDictData> classArray = DictUtils.getDictCache("scheduling_class_info");
        Map<String, String> classMap = classArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));


        List<RollPackingDto> list = rollPackingMapper.getAllList(rollPackingVo);

        for (RollPackingDto entity : list) {
            entity.setPrintStatusDict(printStatusMap.get(entity.getPrintStatus()));
            entity.setClassDifferenceDict(classMap.get(entity.getClassDifference()));
        }
        return list;
    }

    /**
     * 勾选打包
     *
     * @param ids
     * @return
     */
    @Override
    public List<RollPackingDto> getViewById(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<RollPackingDto> viewById = rollPackingMapper.getViewById(idList);

        String splittingOrderNumber = viewById.get(0).getSplittingOrderNumber();
        boolean isTrue = true;
        for (RollPackingDto entity : viewById) {
            if (!splittingOrderNumber.equals(entity.getSplittingOrderNumber())) {
                isTrue = false;
                break;
            }
        }
        if (isTrue) {
            viewById.get(0).setSmallRollsNumber(idList.size());
            return viewById;
        } else {
            throw new GlobalException("勾选的数据不为同一分切制令单");
        }
    }

    /**
     * 小卷不良
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean badSmallRoll(Long id) {

        RollPacking rollPacking = getById(id);
        //获取分切制令单数据
        CutOrdersDocument cutOrdersDocument = cutOrdersDocumentMapper.selectOne(new QueryWrapper<CutOrdersDocument>().lambda().eq(CutOrdersDocument::getSplittingOrderNumber, rollPacking.getSplittingOrderNumber()));

        if (rollPacking.getPrintStatus() == 2) {
            //操作小卷不良后，小卷信息从当前页面消失，传递到生产冻结页面
            QualityProductionFreezeVo qualityProductionFreezeVo = new QualityProductionFreezeVo();
            qualityProductionFreezeVo
                    .setMaterialCode(rollPacking.getMaterialCode())
                    .setProductionLine(cutOrdersDocument.getLineTypeName())
                    .setOrderNo(rollPacking.getSplittingOrderNumber())
                    .setProductNumber(rollPacking.getSmallVolumeNumber());
            boolean b = qualityFeginService.smallRollAdd(qualityProductionFreezeVo);
            if (b) {
                //删除小卷数据
                return removeById(rollPacking);
            } else {
                throw new GlobalException("删除小卷数据失败");
            }
        } else {
            throw new GlobalException("只能操作已打印的小卷");
        }
    }

    /**
     * 补打标签
     *
     * @param id
     * @return
     */
    @Override
    public RollPackingDto retag(Long id) {

        RollPackingDto viewById = rollPackingMapper.getRetagViewById(id);
        //已打印的小卷才可以进行补打标签操作
        if ("2".equals(viewById.getPrintStatus())) {
            return viewById;
        } else {
            throw new GlobalException("已打印的小卷才可以进行补打标签操作");
        }
    }


    /**
     * 修改勾选数据打印状态
     *
     * @param idsVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(IdsVo idsVo) {
        List<String> idList = Arrays.asList(idsVo.getIds().split(","));
        List<RollPacking> rollPackingList = rollPackingMapper.selectList(new QueryWrapper<RollPacking>().lambda().in(RollPacking::getId, idList));
        for (RollPacking entity : rollPackingList) {
            entity.setPrintStatus(2);
            entity.setTemplateId(idsVo.getTemplateId());
        }
        return updateBatchById(rollPackingList);
    }


    /**
     * 修改接头
     *
     * @param jointVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateJoint(JointVo jointVo) {
        List<UpdateJointVo> updateJointList = jointVo.getUpdateJointList();
        if (updateJointList.size() > 0) {
            for (UpdateJointVo entity : updateJointList) {
                RollPacking byId = getById(entity.getId());
                //修改接头数
                byId.setJoint(entity.getJointNum());
                updateById(byId);
            }
            return true;
        }
        return false;
    }

    /**
     * 修改接头回显
     *
     * @param ids
     * @return
     */
    @Override
    public List<RollPacking> jointView(String ids) {
        List<String> strings = Arrays.asList(ids.split(","));

        return rollPackingMapper.selectList(new QueryWrapper<RollPacking>().lambda().in(RollPacking::getId, strings));
    }

    /**
     * 打包标签
     *
     * @param packageLabelVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean packageLabel(PackageLabelVo packageLabelVo) throws Exception {
        //判断勾选的条数
        List<RollPackingDto> rollPackList1 = packageLabelVo.getRollPackList();

        if (rollPackList1 == null) {
            throw new GlobalException("至少勾选一条数据");
        }
        //判断勾选的数据是否幅宽一致
        String width = rollPackList1.get(0).getWidth();
        String splittingOrderNumber = rollPackList1.get(0).getSplittingOrderNumber();

        for (RollPackingDto entity : rollPackList1) {
            if (!width.equals(entity.getWidth())) {
                throw new GlobalException("勾选的数据幅宽不一致");
            }
            if (!splittingOrderNumber.equals(entity.getSplittingOrderNumber())) {
                throw new GlobalException("勾选的数据不属于同一分切制令单");
            }
        }
        List<Long> ids = new ArrayList<>();
        //删除勾选的小卷打包数据
//            List<RollPackingDto> rollPackList = packageLabelVo.getRollPackList();
        for (RollPackingDto entity : rollPackList1) {
            ids.add(entity.getId());
        }

        //判断勾选的条数和填写的每包小卷数
        int listSize = packageLabelVo.getRollPackList().size();
        List<String> packSmallRolls = Arrays.asList(packageLabelVo.getPackSmallRolls().split(","));
        int i = 0;
        for (String entity : packSmallRolls) {
            i = i + Integer.parseInt(entity);
        }
        //判断能否被整除
        if (listSize % i != 0) {
            throw new GlobalException("勾选的数量和每包小卷数不能整除");
        }
        //生成成品称重数据
        boolean add = weighingFinishedMaterialProductService.add(packageLabelVo);
        if (add) {
//            List<Long> ids = new ArrayList<>();
//            //删除勾选的小卷打包数据
////            List<RollPackingDto> rollPackList = packageLabelVo.getRollPackList();
//            for (RollPackingDto entity : rollPackList1) {
//                ids.add(entity.getId());
//            }
            //将要删除的小卷数据存入小卷历史数据
            List<RollPacking> rollPackings = rollPackingMapper.selectList(new QueryWrapper<RollPacking>().lambda().in(RollPacking::getId, ids));
            List<RollPackingHistory> rollPackingHistoryList = new ArrayList<>();
            for (RollPacking entity : rollPackings) {
                RollPackingHistory rollPackingHistory = new RollPackingHistory();
                BeanUtils.copyProperties(entity, rollPackingHistory);
                rollPackingHistoryList.add(rollPackingHistory);
            }
            rollPackingHistoryService.saveBatch(rollPackingHistoryList);
            //删除小卷数据
            rollPackingMapper.deleteBatchIds(ids);
        }
        return add;
    }

    /**
     * 查询小卷关联的母卷
     *
     * @param masterVolumeNumber
     * @return 产品追溯 远程调用
     */
    @Override
    public List<RollPackingDto> selectMasterVolumeNumberList(String masterVolumeNumber) {
        return rollPackingMapper.selectMasterVolumeNumberList(masterVolumeNumber);
    }

    /**
     * 根据小卷号码查询小卷信息
     *
     * @param materialNumber
     * @return 产品追溯 远程调用
     */
    @Override
    public RollPackingDto getTraceabilityRollInfo(String materialNumber) {
        return rollPackingMapper.getRollTraceabilityInfo(materialNumber);
    }

}
